import useAsyncFn from 'hooks/useAsyncFn'
import React, { Fragment, memo, useCallback, useContext, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { ACTIONS, PlayMusicContext } from 'reducers/playMusic'
import { IMusic } from 'apis/types/business'

import { createMusic } from 'helpers/business'
import songlistApi from 'apis/songlist'
import styles from './style.module.css'
import { Spinner } from '@blueprintjs/core'
import BasicInfo from './BasicInfo'
import Tabs from 'components/Tabs'
import { TABS } from 'constants/songList'
import MusicList from 'components/MusicList'
const SonglistDetail = memo(() => {
  const playDispatch = useContext(PlayMusicContext)[1]
  const { songlistId } = useParams<IDictionary<string>>()
  const [state, getSongListDetailFn] = useAsyncFn(songlistApi.getSonglistDetail)
  const { value: res, loading } = state
  const songs = res?.songs as IMusic[]
  const songlist = res?.songlist
  useEffect(() => {
    getSongListDetailFn(Number(songlistId))
  }, [songlistId])
  const playAll = useCallback(
    (autoPlay?: boolean) => {
      const playList = songs.map((v) => {
        return createMusic({
          ...v,
          duration: v.duration / 1000,
        })
      })
      playDispatch({
        type: ACTIONS.SET_PLAY_LIST,
        payload: {
          playList,
        },
      })
      if (autoPlay) {
        const item = playList[0]
        playDispatch({
          type: ACTIONS.PLAY,
          payload: {
            music: item,
            musicId: item.id,
          },
        })
      }
    },
    [songs],
  )
  return (
    <div className={styles.root}>
      {loading ? (
        <Spinner />
      ) : (
        <Fragment>
          <BasicInfo data={songlist} onPlayAll={playAll} />
          <div className={styles.tabs}>
            <Tabs tabs={TABS} />
          </div>
          <MusicList data={songs} onPlayAll={playAll} />
        </Fragment>
      )}
    </div>
  )
})

export default SonglistDetail
